import { ref } from 'vue'
import { UseNamespace } from '../shared/hooks/useNamespace'
import { AccordionItem } from './accordion-types'

export const accordionElements = (ns: UseNamespace, data: AccordionItem, allData: AccordionItem[], clickHandle: (item: AccordionItem) => void, hierarchy: number = 0) => {
  const defaultAllDataActive = (items: AccordionItem[]) => {
    items.map((item) => {
      item.active = false
      if (item.children) defaultAllDataActive(item.children)
    })
  }
  const onClick = (event: Event, hasChild: boolean) => {
    event.stopPropagation()
    if (hasChild) {
      data.open = !data.open
    } else {
      defaultAllDataActive(allData)
      data.active = true
      clickHandle(data)
    }
  }
  const accordionChildren = () => {
    hierarchy++
    if (data.children) {
      const children = data.children.map((item: AccordionItem, index: number) => {
        return accordionElements(ns, item, allData, clickHandle, hierarchy)
      })
      return (
        <>
          <div class={[ns.m('item'), ns.is('open', data.open)]} onClick={(event) => onClick(event, true)}>
            <div class={[ns.m('label')]} style={{ 'text-indent': hierarchy * 20 - 20 + 'px' }}>
              {data.label}
              <div class={[ns.m('open-icon')]}>
                <i class="fa fa-angle-down"></i>
              </div>
            </div>
            <div class={[ns.m('splitter')]} style={{ left: hierarchy * 20 - 10 + 'px' }}></div>
            <div class={[ns.m('items')]}>{children}</div>
          </div>
        </>
      )
    } else {
      return (
        <div class={[ns.m('item'), ns.is('active', data.active)]} onClick={(event) => onClick(event, false)}>
          <div class={[ns.m('label')]} style={{ 'text-indent': hierarchy * 20 - 20 + 'px' }}>
            {data.label}
          </div>
          <div class={[ns.m('splitter')]} style={{ left: hierarchy * 20 - 10 + 'px' }}></div>
        </div>
      )
    }
  }
  return <>{accordionChildren()}</>
}
